//
// Created by 文道江 on 15/11/24.
// Copyright (c) 2015 文道江. All rights reserved.
//

#import "HybridLocationManagerAction.h"


@implementation HybridLocationManagerAction {
    BOOL watching;
}

/**
 * 获取当前位置
 */
- (void)getCurrentLocation:(id)params {

    double distanceFilter = [params[@"distanceFilter"] doubleValue];
    if (distanceFilter == 0.0){
        distanceFilter = 1.0f;
    }

    [self start:^(CLLocationCoordinate2D location, NSError *error) {
        if (error == nil){
            NSLog(@"position: %lf,%lf", location.latitude, location.longitude);
            [self callback:YES data:@{
                    @"latitude" : @(location.latitude),
                    @"longitude" : @(location.longitude)
            }];
            _currentCallback = nil;
        }else{
            [self callback:NO data:error.domain];
        }
        [self stop];
    } distanceFilter: distanceFilter];
}

/**
 * 监听位置
 */
- (void)watchPosition:(id)params {
    watching = YES;
    double distanceFilter = [params[@"distanceFilter"] doubleValue];
    if ( distanceFilter == 0.0){
        distanceFilter = 1.0f;
    }
    [self start:^(CLLocationCoordinate2D location, NSError *error) {
        if (error == nil){
            NSLog(@"position: %lf,%lf", location.latitude, location.longitude);
            //[self dispatchEvent:@"watchPositionChanged" data:@{@"latitude" : @(location.latitude), @"longitude" : @(location.longitude)}];

            [self callback:YES data:@{
                    @"latitude" : @(location.latitude),
                    @"longitude" : @(location.longitude)
            }];
        }else{
            NSLog(@"watchPosition error: %@", params);
            [self callback:NO data:error.domain];
        }
    } distanceFilter: distanceFilter];
}

/**
 * 停止监听位置
 */
- (void)stopWatch:(id)params{
    watching = NO;
    [self stop];
    [self callback:YES data:nil];
}


#pragma mark 定位管理

- (void)start:(void (^)(CLLocationCoordinate2D, NSError *))callback distanceFilter:(double) distanceFilter{

    _currentCallback = callback;
    _location = CLLocationCoordinate2DMake(0.0l, 0.0l);

    if (_locationManager == nil){
        _locationManager = [[CLLocationManager alloc] init];
    }else{
        [_locationManager stopUpdatingLocation];
    }
    if (![CLLocationManager locationServicesEnabled]) {
        NSLog(@"定位服务当前可能尚未打开，请设置打开！");
        _currentCallback(_location, [NSError errorWithDomain:@"定位服务当前可能尚未打开，请设置打开！" code:0 userInfo:@{}]);
        return;
    }
    //如果没有授权则请求用户授权
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
        NSLog(@"无定位权限!");
        if ([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [_locationManager requestWhenInUseAuthorization];
        }
        if ([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            [_locationManager requestAlwaysAuthorization];
        }
        /*if ([_locationManager respondsToSelector:@selector(requestLocation)]) {
            [_locationManager requestLocation];
        }*/
    }

    //设置代理
    _locationManager.delegate = self;
    //设置定位精度
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;

    //定位频率,每隔多少米定位一次
    _locationManager.distanceFilter = distanceFilter;
    //启动跟踪定位
    NSLog(@"开始定位 distanceFilter %lf", distanceFilter);
    [_locationManager startUpdatingLocation];
}

- (void)stop{
    if (_locationManager != nil){
        [_locationManager stopUpdatingLocation];
        //_locationManager = nil;
        NSLog(@"stop 定位 ");
    }
}

#pragma mark CLLocationManagerDelegate<br>/**<br>* 获取经纬度<br>*/

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    CLLocation *currLocation = [locations lastObject];
    //[_locationManager stopUpdatingLocation];
    _location = currLocation.coordinate;
    if (_currentCallback != nil) {
        _currentCallback(_location, nil);
        if (!watching){
            _currentCallback = nil;
            [self stop];
        }
    }
    [self dispatchEvent:@"watchPositionChanged" data:@{@"latitude" : @(_location.latitude), @"longitude" : @(_location.longitude)}];
    NSLog(@"didUpdateLocations %lf, %lf", _location.latitude, _location.longitude);
}

- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading {
    NSLog(@"didUpdateHeading");

}

/**
 *定位失败，回调此方法
 */

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    if ([error code] == kCLErrorDenied) {
        NSLog(@"访问被拒绝");
        _currentCallback(_location, [NSError errorWithDomain:@"访问定位服务被拒绝" code:0 userInfo:@{}]);
        return;
    }
    if ([error code] == kCLErrorLocationUnknown) {
        NSLog(@"无法获取位置信息");
        _currentCallback(_location, [NSError errorWithDomain:@"无法获取位置信息" code:0 userInfo:@{}]);
        return;
    }
    if (_currentCallback != nil) {
        _currentCallback(_location, nil);
        _currentCallback = nil;
    }
    watching = NO;
    NSLog(@"error %@", [error description]);
}

@end